/**
 * 系统编译环境相关中间件
 *
 * Created by snowingsea on 2020/11/02.
 */
const projects = require('./../../models/projects');
const environments = require('./../../models/environments');
const PhoenixError = require('./../../models/phoenix-error');

/**
 * 要求系统编译环境项目存在，不存在时将添加
 * @param req
 * @param res
 * @param next
 */
function requireSystemEnvironmentProjectExist(req, res, next) {
  const options = { creatorId: req.$superUser._id }; // eslint-disable-line no-underscore-dangle
  req.query.language = 'c';
  req.query.projectType = 'gcc';
  projects.getProjects({}, options)
    .then((resProjects) => {
      if (!resProjects || resProjects.length === 0) {
        const { language, projectType } = req.query;
        return projects.addProject(options.creatorId, '', language, projectType, 'gcc');
      }
      return Promise.resolve(resProjects[0]);
    })
    .then((project) => {
      req.$systemEnvironmentProject = project;
      next();
    })
    .catch((err) => {
      next(new PhoenixError(err));
    });
}

/**
 * 判断URL参数中编译环境Id是否存在
 * @param req
 * @param res
 * @param next
 */
function requireEnvironmentExist(req, res, next) {
  if (!req.params.environmentId) {
    next(new PhoenixError('invalid request', 'Missing parameters. "environmentId" is required'));
    return;
  }

  environments.getEnvironment(req.params.environmentId)
    .then((environment) => {
      if (!environment) {
        return Promise.reject(new PhoenixError('not found', 'Not found, environment not found'));
      }
      req.$environment = environment;
      return Promise.resolve();
    })
    .then(() => {
      next();
    })
    .catch((err) => {
      next(new PhoenixError(err));
    });
}

/**
 * 获取编译环境信息
 * @param req
 * @param res
 * @param next
 */
function getEnvironment(req, res, next) { // eslint-disable-line no-unused-vars
  res.json(environments.getJson(req.$environment));
}

/**
 * 批量获取系统编译环境列表
 * @param req
 * @param res
 * @param next
 */
function getSystemEnvironments(req, res, next) {
  const resEnvironments = {
    pagination: req.filter,
  };
  const options = environments.getEnvironmentOptions(req.query);
  options.projectId = req.$systemEnvironmentProject._id; // eslint-disable-line no-underscore-dangle
  environments.filter(req.filter, options)
    .then((data) => {
      resEnvironments.environments = data.map((env) => environments.getSummaryJson(env));
      return environments.getCount(options);
    })
    .then((count) => {
      resEnvironments.pagination.total = count;
      res.json(resEnvironments);
    })
    .catch((err) => {
      next(new PhoenixError(err));
    });
}

/**
 * Export model definition object.
 */
module.exports = {
  requireSystemEnvironmentProjectExist,
  requireEnvironmentExist,

  getEnvironment,
  getSystemEnvironments,
};
